package com.easy.carl.algorithm.String;

/**
 * 剑指 Offer 58 - II. 左旋转字符串
 */
public class ReverseLeftWords58 {

    public String reverseLeftWords1(String s, int n) {
        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        sb.append(chars, n, chars.length - n);
        sb.append(chars, 0, n);
        return sb.toString();
    }

    public String reverseLeftWords(String s, int n) {
        char[] chars = s.toCharArray();
        //翻转前半部分
        reverseArray(chars, 0, n - 1);
        //翻转后半部分
        reverseArray(chars, n, chars.length - 1);
        //翻转整个字符串
        reverseArray(chars, 0, chars.length - 1);
        return String.valueOf(chars);
    }

    /**
     * 翻转数组的指定索引之间的字符
     *
     * @param chars
     * @param start
     * @param end
     */
    public void reverseArray(char[] chars, int start, int end) {
        while (start < end) {
            char c = chars[start];
            chars[start] = chars[end];
            chars[end] = c;
            start++;
            end--;
        }
    }


    public static void main(String[] args) {
        ReverseLeftWords58 reverseLeftWords58 = new ReverseLeftWords58();
        System.out.println(reverseLeftWords58.reverseLeftWords("abcdef", 2));
    }
}
